In [1]:
from ipyleaflet import (
    Map,
    Marker,
    TileLayer, ImageOverlay,
    Polyline, Polygon, Rectangle, Circle, CircleMarker,
    GeoJSON,
    DrawControl
)

from ipywidgets import jslink, IntSlider

from traitlets import link

In [2]:
m = Map(center=[34.6252978589571, -77.34580993652344], layout={'width': '600px', 'height': '300px'})
zoom_slider = IntSlider(description='Zoom', min=3, max=17, value=10)
jslink((zoom_slider, 'value'), (m, 'zoom'))
m



In [3]:
zoom_slider



In [4]:
m.zoom


Out[4]:
10

Now create the DrawControl and add it to the Map using add_control. We also register a handler for draw events. This will fire when a drawn path is created, edited or deleted (there are the actions). The geo_json argument is the serialized geometry of the drawn path, along with its embedded style.


In [5]:
dc = DrawControl()

def handle_draw(self, action, geo_json):
    print(action)
    print(geo_json)

dc.on_draw(handle_draw)
m.add_control(dc)

In addition, the DrawControl also has last_action and last_draw attributes that are created dynamicaly anytime a new drawn path arrives.


In [6]:
dc.last_action


Out[6]:
''

In [7]:
dc.last_draw


Out[7]:
{'geometry': None, 'type': 'Feature'}

Let's draw a second map and try to import this GeoJSON data into it.


In [8]:
m2 = Map(layout={'width': '600px', 'height': '400px'}, center=[34.6252978589571, -77.34580993652344], zoom=m.zoom)
m2


We can use link to synchronize traitlets of the two maps:


In [9]:
map_center_link = link((m, 'center'), (m2, 'center'))
map_zoom_link = link((m, 'zoom'), (m2, 'zoom'))

In [10]:
new_poly = GeoJSON(data=dc.last_draw)

In [11]:
m2.add_layer(new_poly)

Note that the style is preserved! If you wanted to change the style, you could edit the properties.style dictionary of the GeoJSON data. Or, you could even style the original path in the DrawControl by setting the polygon dictionary of that object. See the code for details.

Now let's add a DrawControl to this second map. For fun we will disable lines and enable circles as well and change the style a bit.


In [12]:
dc2 = DrawControl(polygon={'shapeOptions': {'color': '#0000FF'}}, polyline={},
                  circle={'shapeOptions': {'color': '#0000FF'}})
m2.add_control(dc2)

In [ ]:


In [ ]: